package cn.aylog.springboot.service.impl;

import cn.aylog.common.entity.R;
import cn.aylog.springboot.entity.Course;
import cn.aylog.springboot.entity.CourseDescription;
import cn.aylog.springboot.entity.vo.CourseVo;
import cn.aylog.springboot.service.ICourseDescriptionService;
import cn.aylog.springboot.service.ICourseService;
import cn.aylog.springboot.service.ICourseVoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CourseVoServiceImpl implements ICourseVoService {

    @Resource
    private ICourseService courseService;

    @Resource
    private ICourseDescriptionService descriptionService;

    @Override
    public String addCourseVo(CourseVo vo) {
        Course course = new Course();
        BeanUtils.copyProperties(vo, course);
        boolean success = courseService.save(course);
        if(!success) {
            return "";
        }
        CourseDescription description = new CourseDescription();
        description.setId(course.getId());
        description.setDescription(vo.getDescription());
        success = descriptionService.save(description);
        if(!success) {
            return "";
        }
        return course.getId();
    }

    @Override
    public List<CourseVo> queryByIds(List<String> ids) {
        List<Course> courses = courseService.listByIds(ids);
        if(courses.isEmpty()) {
            return null;
        }
        List<CourseDescription> list = descriptionService.listByIds(ids);
        Map<String, CourseDescription> map = new HashMap<>();
        if(!list.isEmpty()) {
            list.forEach(i -> map.put(i.getId(), i));
        }
        List<CourseVo> vos = new ArrayList<>();
        courses.forEach(course -> {
            CourseVo vo = new CourseVo();
            BeanUtils.copyProperties(course, vo);
            if (map.containsKey(course.getId())) {
              vo.setDescription(map.get(course.getId()).getDescription());
            }
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public boolean updateCourseVo(CourseVo vo) {
        Course course = new Course();
        BeanUtils.copyProperties(vo, course);
        boolean success = courseService.updateById(course);
        if(!success) {
            return false;
        }
        CourseDescription description = new CourseDescription();
        description.setId(course.getId());
        description.setDescription(vo.getDescription());
        success = descriptionService.updateById(description);
        return success;
    }
}
